//
//  NetworkTool.swift
//  weibo
//
//  Created by Qing on 2017/5/19.
//  Copyright © 2017年 成哥哥. All rights reserved.
//

import UIKit
import AFNetworking
import AFNetworking

//使用枚举定义get、 post
enum HMRequestMethod: String {
    case get = "get"
    case post = "post"
}



class NetworkTool: AFHTTPSessionManager {
    
    //MARK: - 应用程序相关
//    let appKey = "3454493309"
//    let appSecret = "7520eda18d618dfef9cb05937679f88c"
//    let redirectURI = "http://Baidu.com"

//        let appKey = "2582604910"
//        let appSecret = "2a9750e6ebffe31da5b1ce87d2e5a38d"
//        let redirectURI = "http://Baidu.com"
    
        let appKey = "2462653817"
        let appSecret = "6ef4711dd0fdf38f2a91e7d186a53138"
        let redirectURI = "http://Baidu.com"
    
    /// 网络请求的回调, typealias - 自定义类型
    typealias HMRequestCallBack = (_ result: Any?, _ error: Error?) -> ()
    
    
    /// 单例
    static let sharedTool: NetworkTool = {
    
        let tool = NetworkTool(baseURL: nil)
        
        //添加序列化格式
//        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
}

// MARK: - 请求用户首页信息
extension NetworkTool{
    
    
    /// 加载用户首页信息
    ///
    /// - Parameter finished: 完成回调，true加载成功，false为失败
    /// - get - [http://open.weibo.com/wiki/2/statuses/user_timeline](http://open.weibo.com/wiki/2/statuses/user_timeline)
    func loadStatuses(finished: @escaping HMRequestCallBack) {
        
        let urlSting = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        /// 从帐户模型获取token，并转化为字典参数。
         var tokenDics: [String: Any]? {
            
            if let token = UserAccountViewModel.sharedUserAccount.accountToken {
                
                return ["access_token": token]
                
            }
            return nil
        }
        
        NetworkTool.sharedTool.request(method: .get, URLString: urlSting, parameters: tokenDics) { (result, error) in
            
            if error != nil {
                print("token出错了")
                finished(nil, NSError(domain: "www.chucuo", code: 101, userInfo: ["message" : "token出错了"]))
                return
            }
            
            print("NetworkToll的Token：\(tokenDics)")
            finished(result, nil)
            
        }
        
    }
    
}


// MARK: - 请求用户信息
extension NetworkTool {

    
    /// 从帐户模型获取token，并转化为字典参数。
    private var tokenDic: [String: Any]? {
        
        if let token = UserAccountViewModel.sharedUserAccount.accountToken {
        
        return ["access_token": token]
            
        }
        return nil
    }
    
    
    /// 根据用户ID请求用户信息。
    ///
    /// - Parameters:
    ///   - access_token: access_token
    ///   - uid: uid
    ///   - finished: 请求的回调
    /// get - [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInFo(uid: String, finished: @escaping HMRequestCallBack) {
        
        
        /// 守卫，如果token数组有值，则继续执行下面的代码。如果没有值，则输出错误信息。
        guard var  params = tokenDic else {
            
//            finished(request, NSError(domain: "cn.itcast.error", code: -100, userInfo: ["message": "token 为空"])
            print("token错误")
            
            finished(nil, NSError(domain: "cn.itcast.error", code: -100, userInfo: ["message": "token 错误"]))
            
            return
        }
        
        //发起请求的URL
        let urlString = "https://api.weibo.com/2/users/show.json"
        //添加uid到数组，发起请求的参数。
        params["uid"] = uid
        //发起get请求
        NetworkTool.sharedTool.request(method: .get, URLString: urlString, parameters: params, finished: finished)
//        NetworkTool.sharedTool.getRequests(url: urlString, finished: finished)
    }

}

//MARK: - OAuth相关
extension NetworkTool {


    /// 请求授权URL
    /// set - [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: URL {
    
        //拼接URL
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"
    
//        print("urlString回调\(urlString)")
        return URL(string: urlString)!
        
    }
    
    /// 加载AccessToken
    ///
    /// - Parameters:
    ///   - code: 授权后 获得的令牌
    ///   - finished: 回调
    /// - set : [http://open.weibo.com/wiki/Oauth2/access_token](http://open.weibo.com/wiki/Oauth2/access_token)
    func LoadAccessToKen(code: String, finished: @escaping HMRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        
        /// post请求必要参数
        let params = ["client_id": appKey,
                     "client_secret": appSecret,
                     "grant_type": "authorization_code",
                     "code": code,
                     "redirect_uri": redirectURI,]
        
        //发起请求
        request(method: .post, URLString: urlString, parameters: params, finished: finished)
        
//        getRequests(url: urlString, finished: finished)
        
        
        
        /* 查看json 返回的value数据类型
        //测试返回的数据内容： AFN 默认响应格式是JSON ， 会直接反序列化
        //如果要确认数据格式的问题，
        //1> 设置相应数据格式是二进制的。如果value没有带""号，则是NSNumber类型。
        responseSerializer = AFHTTPResponseSerializer()
        
        //2> 发起网络请求
        post(urlString, parameters: params, progress: nil, success: { (_, result) in
            
            //3> 将二进制数据转换成字符串
            let json = NSString(data: result as! Data, encoding: String.Encoding.utf8.rawValue)
            
//            print(json)
//            {"access_token":"2.00bHuOpGBWhmlD56e752962cb44pZE",
//             "remind_in":"157679999",
//             "expires_in":157679999,
//             "uid":"6253942455"}
            
        }, failure: nil)
        */

        }
}

//封装AFN方法
extension NetworkTool {

    
    /// 网络请求
    ///
    /// - Parameters:
    ///   - method: 请求方式 get or post 使用枚举分类
    ///   - URLString: 请求的网址baseURL
    ///   - parameters: 请求参数，以字典的形式
    ///   - finished: 回调参数
    fileprivate func request(method: HMRequestMethod, URLString: String, parameters: [String: Any]?, finished: @escaping HMRequestCallBack) {
        
        //定义成功回调
        let success = {(_ data: URLSessionDataTask, _ result: Any) -> () in
            
            finished(result, nil)
        }
        
        //定义失败回调
        let failure = {(_ data: URLSessionDataTask?, _ error: Error) -> () in
            print("Netowrk请求回调失败")
            finished(data, error)
            print(error)
        }
        
        //定义请求
        if method == HMRequestMethod.get {
        
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        } else {
        
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }
    
    }
}



// MARK: - 原生的Get请求方法
extension NetworkTool {
    
    
    /// Get请求
    ///
    /// - Parameters:
    ///   - url: url
    ///   - finished: 请求回调
    fileprivate func getRequests(url: String, finished: @escaping HMRequestCallBack) {
        
        let url = URL(string: url)
        let session = URLSession.shared

        let dataTask = session.dataTask(with: url!) { (data, _, error) in
            
            if let data = data {
                
                let result = String(data: data, encoding: .utf8)
            
                finished(result, nil)
            
            } else {
            
                finished(nil, error)
            }
        }
        
        dataTask.resume()
    
    }

}
